package com.example.dangerouscargodriver.ui.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.example.dangerouscargodriver.R;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.entry.MyResourceDetailInfo;
import com.example.dangerouscargodriver.entry.PublishInfo;
import com.example.dangerouscargodriver.entry.ReckonInfo;
import com.example.dangerouscargodriver.module.ResourceRecordInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.utils.TextUtils;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.widget.LoadingDialog;
import com.example.dangerouscargodriver.widget.ModifyPriceBottomDialog;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;

public class MyResourceInfoEditActivity extends HttpRequestActivity implements View.OnClickListener {

    private static final String TAG = "MyResourceInfoEditActivity";
    private static final int RESPONSE_GET_RECKON_INFO = 0;

    private ActionBar mActionBar = null;
    private TextView mProtocol = null;
    private TextView mAmountOfMoney = null;
    private TextView mOfflineSelector = null;
    private TextView mOnlineSelector = null;
    private TextView mOfflineProtocol = null;

    private TextView mGiveBackSelector = null;
    private TextView mNotGiveBackSelector = null;
    private TextView mDepositNull = null;
    private EditText mDeposit = null;
    private TextView mPublishInfoAction = null;
    private TextView mTruckClassMeta = null;
    private TextView mTruckType = null;
    private TextView mNeedToPay = null;
    private TextView mStartAddress = null;
    private TextView mEndAddress  = null;
    private LinearLayout mOnlineNeedView = null;
    private LinearLayout mOfflineNeedView = null;
    private TextView mMoneyModify = null;
    private TextView mSourceDistance = null;
    private EditText mCommentInfo = null;
    private TextView mCommentHD = null;
    private TextView mCommentFP = null;
    private TextView mCommentUnloadTwo = null;
    private TextView mCommentUnloadMulti = null;
    private TextView mStartBoardingTime = null;
    private TextView mStopBoardingTime = null;

    private MyResourceDetailInfo mResourceDetailInfo = null;
    private ReckonInfo mReckonInfo = null;
    private int mPayType = 2; //1： 线下支付 2：线上支付
    private PublishInfo mPublishInfo = null;
    private boolean mProtocolAgreed = false;
    private LoadingDialog mLoadingDialog = null;

    @SuppressLint("LongLogTag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(PublishResourceStepTwoActivity.class);
        setContentView(R.layout.activity_my_resource_info_edit);

        mLoadingDialog = new LoadingDialog(this);
        //获取传递过来的数据结构
        mResourceDetailInfo = (MyResourceDetailInfo)getIntent().getSerializableExtra("info");

        //初始化页面元素
        mProtocol = findViewById(R.id.tv_protocol);
        mAmountOfMoney = findViewById(R.id.tv_amount_of_money);
        mAmountOfMoney.setText(mResourceDetailInfo.getExpected_price());
        mSourceDistance = findViewById(R.id.tv_source_distance);
        mSourceDistance.setText(mResourceDetailInfo.getSource_distance() + "公里");
        mNeedToPay = findViewById(R.id.tv_need_to_pay);
        mNeedToPay.setText(mResourceDetailInfo.getExpected_price());
        mMoneyModify = findViewById(R.id.text_money_modify);
        mMoneyModify.setOnClickListener(this);

        mOfflineSelector = findViewById(R.id.tv_pay_offline_selector);
        mOfflineSelector.setOnClickListener(this);
        mOfflineProtocol = findViewById(R.id.tv_pay_offline_protocol);
        mOnlineSelector = findViewById(R.id.tv_pay_online_selector);
        mOnlineSelector.setOnClickListener(this);
        mGiveBackSelector = findViewById(R.id.tv_deposit_giveback);
        mGiveBackSelector.setOnClickListener(this);
        mNotGiveBackSelector = findViewById(R.id.tv_deposit_not_giveback);
        mNotGiveBackSelector.setOnClickListener(this);
        mDepositNull = findViewById(R.id.tv_deposit_null);
        mDepositNull.setOnClickListener(this);

        mDeposit = findViewById(R.id.ed_deposit);
        mPublishInfoAction = findViewById(R.id.btn_publish_info);
        mPublishInfoAction.setOnClickListener(this);

        mCommentHD = findViewById(R.id.tv_comment_hd);
        mCommentHD.setOnClickListener(this);
        mCommentFP = findViewById(R.id.tv_comment_fp);
        mCommentFP.setOnClickListener(this);
        mCommentUnloadTwo = findViewById(R.id.tv_comment_unload_two);
        mCommentUnloadTwo.setOnClickListener(this);
        mCommentUnloadMulti = findViewById(R.id.tv_comment_unload_multi);
        mCommentUnloadMulti.setOnClickListener(this);
        mCommentInfo = findViewById(R.id.tv_comment_info);
        if(mResourceDetailInfo.getRemark() != null){
            mCommentInfo.setText(mResourceDetailInfo.getRemark());
        }

        mTruckClassMeta = findViewById(R.id.tv_truck_class);
        mTruckType = findViewById(R.id.tv_truck_type);
        mTruckClassMeta.setText(mResourceDetailInfo.getTruck_type());
        //直接跳转过来，车辆的类型信息获取不到
        mTruckType.setVisibility(View.GONE);

        mStartAddress = findViewById(R.id.tv_start_address);
        mEndAddress = findViewById(R.id.tv_end_address);
        mStartAddress.setText(mResourceDetailInfo.getFrom_name());
        mEndAddress.setText(mResourceDetailInfo.getTo_name());

        TextUtils.getBuilder().click(getResources().getString(R.string.pay_offline_protocol), getResources().getColor(R.color.liji_c_blue), new TextUtils.OnClickListener() {
            @Override
            public void onClick(int position) {
                switch (position){
                    case 0:
                        Intent intent = new Intent(MyResourceInfoEditActivity.this, ShowHtmlActivity.class);
                        intent.putExtra("type", "1");
                        startActivity(intent);
                        break;
                }
            }
        }, "《危司机平台订金担保规则》").clickInto(mOfflineProtocol);

        TextUtils.getBuilder().click(getResources().getString(R.string.company_partner_protocol_order), getResources().getColor(R.color.liji_c_blue), new TextUtils.OnClickListener() {
            @Override
            public void onClick(int position) {
                switch (position){
                    case 0:
                        Intent intent = new Intent(MyResourceInfoEditActivity.this, ShowHtmlActivity.class);
                        intent.putExtra("type", "3");
                        startActivity(intent);
                        break;
                    case 1:
                        Intent intent1 = new Intent(MyResourceInfoEditActivity.this, ShowHtmlActivity.class);
                        intent1.putExtra("type", "2");
                        startActivity(intent1);
                        break;
                    case 2:
                        Intent intent2 = new Intent(MyResourceInfoEditActivity.this, ShowHtmlActivity.class);
                        intent2.putExtra("type", "1");
                        startActivity(intent2);
                        break;
                    default:
                        break;
                }
            }
        }, "《危司机用户服务协议》", "《危司机隐私政策》", "《危司机平台订金担保规则》").checkBox(this,  mProtocol, new TextUtils.OnImageClickListener() {
            @Override
            public void onChecked() {
                mProtocolAgreed = true;
            }

            @Override
            public void onUnChecked() {
                mProtocolAgreed = false;
            }
        }).clickInto(mProtocol);

        //默认线上支付
        mOnlineNeedView = findViewById(R.id.layout_online_need);
        mOfflineNeedView = findViewById(R.id.layout_offline_need);
        if(mResourceDetailInfo.getPay_type().equals("2")){
            mPayType = 2;
            //线上
            mOnlineNeedView.setVisibility(View.VISIBLE);
            mOfflineNeedView.setVisibility(View.GONE);
            if(Float.parseFloat(mResourceDetailInfo.getDeposit()) > 0){
                mGiveBackSelector.setVisibility(View.VISIBLE);
                mGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
                mNotGiveBackSelector.setVisibility(View.GONE);
                mDeposit.setText(mResourceDetailInfo.getDeposit());

            }
            else{
                mGiveBackSelector.setVisibility(View.VISIBLE);
                mDepositNull.setBackgroundResource(R.drawable.rounded_button);
                mNotGiveBackSelector.setVisibility(View.GONE);
            }
        }
        else{
            //线下
            mPayType = 1;
            mOnlineNeedView.setVisibility(View.GONE);
            mOfflineNeedView.setVisibility(View.VISIBLE);

            if(Float.parseFloat(mResourceDetailInfo.getDeposit()) > 0){
                mGiveBackSelector.setVisibility(View.GONE);
                mNotGiveBackSelector.setVisibility(View.VISIBLE);
                mNotGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
                mDepositNull.setBackgroundResource(R.drawable.rounded_edittext);
                mDeposit.setText(mResourceDetailInfo.getDeposit());
            }
            else{
                mGiveBackSelector.setVisibility(View.GONE);
                mNotGiveBackSelector.setVisibility(View.VISIBLE);
                mNotGiveBackSelector.setBackgroundResource(R.drawable.rounded_edittext);
                mDepositNull.setBackgroundResource(R.drawable.rounded_button);
                mDeposit.setText(mResourceDetailInfo.getDeposit());
            }
        }

        mStartBoardingTime = findViewById(R.id.ed_start_boarding_time);
        mStopBoardingTime = findViewById(R.id.ed_end_boarding_time);
        mStartBoardingTime.setText(mResourceDetailInfo.getLoadtime());
        if(mResourceDetailInfo.getLoadtime2() == null || mResourceDetailInfo.getLoadtime2().equals("")) {
            mStopBoardingTime.setText(mResourceDetailInfo.getLoadtime());
        }
        else{
            mStopBoardingTime.setText(mResourceDetailInfo.getLoadtime2());
        }

        mActionBar = findViewById(R.id.actionBarMyResourceEdit);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @SuppressLint("LongLogTag")
    private void publishRecordInfo(){
        //执行发布货源的操作
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("token", AuthController.Instance().getToken());

        JSONObject resource_param = new JSONObject();
        try {
            resource_param.put("recid", mResourceDetailInfo.getRecid());
            resource_param.put("status", mResourceDetailInfo.getStatus());
            resource_param.put("mobilephone", mResourceDetailInfo.getMobilephone());
            resource_param.put("contact", mResourceDetailInfo.getContact());
            resource_param.put("contact_sex", mResourceDetailInfo.getContact_sex());
            resource_param.put("expected_price_unit", "1");
            resource_param.put("loadtime", mStartBoardingTime.getText().toString());
            if(!mStopBoardingTime.getText().toString().equals("")) {
                resource_param.put("loadtime2", mStopBoardingTime.getText().toString());
            }
            resource_param.put("remark", "");
            resource_param.put("pay_type", Integer.toString(mPayType));
            if(mDeposit.getText().toString().equals("")){
                resource_param.put("deposit", "0.00");
            }
            else {
                resource_param.put("deposit", mDeposit.getText().toString());
            }
            resource_param.put("expected_price", mNeedToPay.getText().toString());
            resource_param.put("weight", mResourceDetailInfo.getWeight());
            resource_param.put("un_batch", mResourceDetailInfo.getUn_batch());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mLoadingDialog.show();

        Log.d(TAG, "resource_param: " + resource_param.toString());
        sendHttpJsonRequest(
                IHttpRequest.RequestMethod.PUT_METHOD,
                RemoteAPI.REQUEST_V1_USER_SG_SOURCE + "/" + mResourceDetailInfo.getRecid(),
                header,
                resource_param,
                RemoteAPICmd.REQUEST_V1_USER_SG_SOURCE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private boolean checkInput(){
        return true;
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.tv_pay_offline_selector){
            if(mPayType == 2){
                v.setBackgroundResource(R.drawable.rounded_button);
                mOnlineSelector.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                mPayType = 1;
            }
            else{
                v.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                mOnlineSelector.setBackgroundResource(R.drawable.rounded_button);
                mPayType = 2;
            }
            mOfflineProtocol.setVisibility(View.VISIBLE);
            mOfflineNeedView.setVisibility(View.VISIBLE);
            mGiveBackSelector.setVisibility(View.GONE);
            mNotGiveBackSelector.setVisibility(View.VISIBLE);
            mNotGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
            mDepositNull.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mOnlineNeedView.setVisibility(View.GONE);
        }
        else if(v.getId() == R.id.tv_pay_online_selector){
            if(mPayType == 2){
                v.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                mOfflineSelector.setBackgroundResource(R.drawable.rounded_button);
                mPayType = 1;
            }
            else{
                v.setBackgroundResource(R.drawable.rounded_button);
                mOfflineSelector.setBackgroundResource(R.drawable.rounded_edittext_home_bg);
                mPayType = 2;
            }
            mOfflineProtocol.setVisibility(View.GONE);
            mOfflineNeedView.setVisibility(View.GONE);
            mOnlineNeedView.setVisibility(View.VISIBLE);
            mGiveBackSelector.setVisibility(View.VISIBLE);
            mGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
            mDepositNull.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mNotGiveBackSelector.setVisibility(View.GONE);
        }
        else if(v.getId() == R.id.tv_deposit_giveback){
            mDepositNull.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
            mNotGiveBackSelector.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mDeposit.setHint(R.string.item_front_money_num);
            mDeposit.setEnabled(true);
        }
        else if(v.getId() == R.id.tv_deposit_not_giveback){
            mDepositNull.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mGiveBackSelector.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mNotGiveBackSelector.setBackgroundResource(R.drawable.rounded_button);
            mDeposit.setHint(R.string.item_front_money_num);
            mDeposit.setEnabled(true);
        }
        else if(v.getId() == R.id.tv_deposit_null){
            mDepositNull.setBackgroundResource(R.drawable.rounded_button);
            mGiveBackSelector.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mNotGiveBackSelector.setBackgroundResource(R.drawable.rounded_edittext_little_radius);
            mDeposit.setText("");
            mDeposit.setHint("");
            mDeposit.setEnabled(false);
        }
        else if(v.getId() == R.id.btn_publish_info){
            if(!mProtocolAgreed){
                ToastUtils.showLongToast(this, "请查看并同意相关的服务协议!");
                return;
            }
            if(checkInput()) {
                publishRecordInfo();
            }
            else{
                ToastUtils.showLongToast(this, "请填写完整的发布信息！");
            }
        }
        else if(v.getId() == R.id.text_money_modify){
            ModifyPriceBottomDialog dialog = new ModifyPriceBottomDialog();
            dialog.setOnItemClickListener(new ModifyPriceBottomDialog.OnItemClickListener() {
                @Override
                public void onConfirm(String price) {
                    if(price!= null && !price.equals("")) {
                        mAmountOfMoney.setText(price);
                        mNeedToPay.setText(price);
                    }
                }

                @Override
                public void onCancel() {

                }
            });
            dialog.showDialog(this);
        }
        else if(v.getId() == R.id.tv_comment_hd){
            mCommentInfo.append(" 需要回单 ");
        }
        else if(v.getId() == R.id.tv_comment_fp){
            mCommentInfo.append(" 需要发票 ");
        }
        else if(v.getId() == R.id.tv_comment_unload_two){
            mCommentInfo.append(" 一装两卸 ");
        }
        else if(v.getId() == R.id.tv_comment_unload_multi){
            mCommentInfo.append(" 一装多卸 ");
        }
        else{
            /**/
        }
    }

    @SuppressLint("LongLogTag")
    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_V1_USER_SG_SOURCE){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    //发布货源成功
                    ToastUtils.showLongToast(getBaseContext(), "编辑货源成功");
                    finish();
                }
                else{
                    //发布货源失败
                    ToastUtils.showLongToast(getBaseContext(), "编辑货源失败");
                }
                mLoadingDialog.dismiss();
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_V1_SG_SOURCE_GOODS){
            mLoadingDialog.dismiss();
        }
        else{

        }
    }
}